package com.guang.springbootexecutordistributedlock.controller;

import com.guang.springbootexecutordistributedlock.distributedlock.DistributedLock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author lg
 * @Description
 * @date 2022/11/3 15:57
 */
@RestController
@RequestMapping(value = "/lock")
public class DistributedLockController {
    private static final Logger logger = LoggerFactory.getLogger(DistributedLockController.class);

    @Resource
    private DistributedLock distributedLock;

    @GetMapping(value = "get")
    public String lock(@RequestParam(value = "lockKey") String lockKey){
        logger.info("请求进来了");
        CountDownLatch countDownLatch = new CountDownLatch(200);
        AtomicInteger count = new AtomicInteger(0);

        for (int i = 0; i < 200; i++) {
            new Thread(()->{
                try {
                    distributedLock.lock(lockKey);
                    for (int i1 = 0; i1 < 50000; i1++) {
                        count.getAndIncrement();
                    }
                    logger.info("-------------->>>当前业务逻辑执行结束<<<--------------");
                    countDownLatch.countDown();
                } catch (Exception e) {
                    logger.error("执行失败，对应错误信息是：{},对应异常信息是：{}",e.getMessage(),e.toString());
                } finally {
                    distributedLock.unlock();
                }
            },"t"+i).start();
        }
        try {
            countDownLatch.await();
            return "success"+count;
        } catch (InterruptedException e) {
            return "defeat"+count;
        }
    }


}
